How to do delayed function calls in Unity3D (one line of code)

Ok, after years of working with ActionScript 3 I got used to use Greensocks superb tweening library “TweenMax” a lot. In my opinion one of the most useful functions is the “delayedCall” method which lets me execute code with some delay (who would have guessed it).

TweenMax (AS3):
TweenMax.delayedCall(2, launchRocket);

Invoke (C#):
I was looking for a “one-liner” to do the same thing in Unity3D using C#. And I found it. It’s called “Invoke” and it’s a method of the MonoBehaviour class which all C# scripts inherit from if they are created within Unity3D.

Invoke("launchRocket", 4);
// triggers the method "launchRocket" after 4 seconds

InvokeRepeating (C#):
To do repeating calls use “InvokeRepeating” and add an additional parameter to set the delay between each call.

InvokeRepeating("launchRocket", 4, 0.5);
// triggers after 4 seconds and does another calls every 0.5 seconds

CancelInvoke (C#):
To cancel use “CancelInvoke” with the method name as parameter. If you want to cancel all invoke calls on a MonoBehaviour don’t pass any name.

CancelInvoke("launchRocket");
//cancels all invoke calls with the given method name

CancelInvoke();
//cancels all invoke calls on the current MonoBehaviour

8 thoughts on “How to do delayed function calls in Unity3D (one line of code)

  1. Thank you for posting this, super helpful! Was tired of having to do a “yield wait”. This is so much easier. You rock!

  2. Very useful, exactly what i needed.
    I used that other method in the matual with yelding and crap, jesus it was horrible. Why is that even there when this exists.

  3. Hello from 2020. This post is still saving people like me tons of time. Just wanted to let you know. Thank you!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.